package org.example;

import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import java.io.*;
import java.net.Socket;
import java.util.Properties;

public class Test {
    private  static String PORT ;
    private  static String ADDRESS;
    private static String IP;
    private static final long POLL_INTERVAL = 3000; // 监听间隔，单位为毫秒

    public static void main(String[] args) throws Exception {
        // 指定需要监听的文件夹路径
        proper();

        // 创建文件变化监听器
        FileAlterationObserver observer = new FileAlterationObserver(new File(ADDRESS));
        observer.addListener(new FileAlterationListenerAdaptor() {
            @Override
            public void onFileCreate(File file) {
                // 监听到文件创建时的处理
                // 将文件上传到服务器的代码逻辑
                try {
                    uploadToServer(file);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("文件已创建：" + file.getName() + "，上传到服务器");
            }

            @Override
            public void onFileChange(File file) {
                // 监听到文件变化时的处理
                // 更新服务器上对应文件的代码逻辑
                // updateServerFile(file);
                System.out.println("文件已变化：" + file.getName() + "，更新服务器文件");
            }

            @Override
            public void onFileDelete(File file) {
                // 监听到文件删除时的处理
                // 删除服务器上同名文件的代码逻辑
                try {
                    deleteFromServer(file);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("文件已删除：" + file.getName() + "，从服务器删除文件");
            }
        });

        // 创建文件变化监视器
        FileAlterationMonitor monitor = new FileAlterationMonitor(POLL_INTERVAL);
        monitor.addObserver(observer);
        // 启动监视器
        monitor.start();
    }
    public static void proper() throws IOException {
        //读取properties
        InputStream inputStream = Client.class.getClassLoader().getResourceAsStream("client.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        //获取端口和地址
        System.out.println("port=" + properties.getProperty("port"));
        System.out.println("address=" + properties.getProperty("address"));
        System.out.println("ip=" + properties.getProperty("ip"));
        PORT = properties.getProperty("port");
        ADDRESS = properties.getProperty("address");
        IP = properties.getProperty("ip");
        inputStream .close();
    }

    // 上传文件到服务器
    private static void uploadToServer(File file) throws IOException {
        String serverIP = IP;
        int serverPort = Integer.parseInt(PORT);

        // 要发送的文件路径
        String filePath = ADDRESS;

        // 连接远程服务端
        try (Socket socket = new Socket(serverIP, serverPort)) {
            // 获取文件类型和内容
            String uploadFileName = file.getName();
            String uploadRequest = "UPLOAD " + uploadFileName;
            byte[] fileContent = getFileContent(file.getAbsolutePath());
            // 发送文件类型
            sendString(socket, uploadRequest);
            // 发送文件内容
            sendBytes(socket, fileContent);
            System.out.println("文件发送成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static byte[] getFileContent(String filePath) throws IOException {
        File file = new File(filePath);
        byte[] fileContent = new byte[(int) file.length()];

        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            fileInputStream.read(fileContent);
        }
        return fileContent;
    }

    private static void sendString(Socket socket, String str) throws IOException {
        OutputStream outputStream = socket.getOutputStream();
        PrintWriter writer = new PrintWriter(outputStream, true);
        writer.println(str);
    }

    private static void sendBytes(Socket socket, byte[] bytes) throws IOException {
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write(bytes);
        outputStream.flush();
    }
    // 更新服务器上对应文件
    private static void updateServerFile(File file) throws IOException {
        uploadToServer(file);
    }
    // 从服务器删除文件
    private static void deleteFromServer(File file) throws IOException {
        // 实现从服务器删除文件的逻辑
        try {
            // 连接远程服务端
            Socket socket = new Socket(IP, Integer.parseInt(PORT));

            // 获取服务端的输出流，并发送删除请求
            OutputStream outputStream = socket.getOutputStream();
            String deletedFileName = file.getName();
            String deleteRequest = "DELETE " + deletedFileName;
            outputStream.write(deleteRequest.getBytes());

            // 关闭连接
            socket.close();

            System.out.println("客户端成功发送删除请求: " + deleteRequest);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
